var express = require("express")
var router = express.Router()
var QcloudSms = require("qcloudsms_js")
var connection = require("../../../db/sql")
var jwt = require("jsonwebtoken")
const bcrypt = require("bcryptjs")
var cartSql = require("./cartSql")
var snowflake = require("./snowflake")

// 添加到商品到用户的购物车
router.post("/api/cart/shopmessage", function (req, res, next) {
  // 获取身份信息，解析token
  let obj = req.body
  console.log(obj)
  let token = req.headers.token
  let tokenObj = jwt.decode(token)
  Object.assign(obj, tokenObj)
  console.log(obj)
  connection.query(cartSql.insertShopMessage(obj), function (err, resluts) {
    if (err) {
      res.send({
        msg: "插入数据失败",
        data: err,
      })
    }

    connection.query(
      cartSql.selectShopMessage(tokenObj),
      function (err, reslut) {
        if (err) {
          res.send({
            status: 203,
            mgs: "出错了",
          })
        }
        res.send({
          status: 200,
          msg: "添加到购物车成功",
          number: reslut.length,
        })
      }
    )
  })
})

// 查询用户购物车信息
router.get("/api/cart/shopusercart", function (req, res, next) {
  let token = req.headers.token
  let tokenObj = jwt.decode(token)
  connection.query(cartSql.selectShopMessage(tokenObj), function (err, reslut) {
    if (err) {
      res.send({
        msg: "查询数据失败",
        data: err,
      })
    }
    res.send({
      status: 200,
      msg: "查询到该用户购物车信息",
      data: reslut,
    })
  })
})

// 删除购物车商品信息
router.post("/api/cart/delshopmessage", function (req, res, next) {
  let id = req.body.id
  connection.query(cartSql.delShopMessage(id), function (err, resluts) {
    if (err) {
      res.send({
        status: 201,
        msg: "删除失败",
        data: err,
      })
    }

    res.send({
      status: 200,
      msg: "删除成功",
      data: resluts,
    })
  })
})

// 购物车订单生成 将购物车数据插入到订单表中
router.post("/api/cart/ordershop", function (req, res, next) {
  let id = JSON.stringify(snowflake.generate())
  console.log(`生成的订单号${id}`)
  let shopDatas = req.body
  let cartShopId = []
  let token = req.headers.token
  let tokenObj = jwt.decode(token)
  // 查询用户id
  connection.query(cartSql.selectUserId(tokenObj), function (err, reslut) {
    if (err) {
      res.send({
        status: 201,
        msg: "查询用户id出错",
        data: err,
      })
    }
    let params = { shopId: id, userId: reslut[0].user_id }

    // 插入订单号数据库操作
    connection.query(
      cartSql.insertOrderNumber(params),
      function (errs, resluts) {
        if (err) {
          res.send({
            status: 202,
            msg: "添加订单号出错",
            data: errs,
          })
        }

        // 获取订单号的id
        connection.query(cartSql.selectOrderId(id), function (error, orderId) {
          if (err) {
            res.send({
              status: 203,
              msg: "查询订单号出错",
              data: error,
            })
          }
          // console.log(orderId[0].ordernumber_id)
          let shopId = { order_id: orderId[0].id }
          for (let key of Object.keys(shopDatas)) {
            // 订单号加入对象中
            Object.assign(shopDatas[key], shopId)
            // console.log(shopDatas[key])
            cartShopId.push(shopDatas[key].id)
            let option = shopDatas[key]
            // 将订单数据插入数据库
            connection.query(
              cartSql.insertOrderFrom(option),
              function (err, datas) {
                if (err) {
                  res.send({
                    status: 204,
                    msg: "插入订单商品数据出错",
                    data: err,
                  })
                }
              }
            )
          }

          // 清空购物车
          console.log(cartShopId)
          cartShopId.forEach((item) => {
            let id = parseInt(item)
            connection.query(
              cartSql.delCartShopMes(id),
              function (err, reslut) {
                if (err) {
                  res.send({
                    code: 207,
                    msg: "清空购物车失败",
                    data: err,
                  })
                }
              }
            )
          })
          res.send({
            code: 200,
            msg: "生成订单成功",
            // data: datas,
          })
        })
      }
    )
  })

  // res.send({
  //   code: 200,
  //   msg: "生成订单号成功",
  //   id,
  // })
})

module.exports = router
